package org.ahuanlien.crm.realms;

import org.ahuanlien.crm.domain.Employee;
import org.ahuanlien.crm.service.IEmployeeService;
import org.ahuanlien.crm.service.IPermissionService;
import org.ahuanlien.crm.service.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {

	public String getName() {
		return "MyRealm";
	}


	@Autowired
	private IEmployeeService employeeService;

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IPermissionService permissionService;


	/**
	 * 授权
	 *
	 * @param principals
	 * @return
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//获取当前登录的用户
		Employee currentUser = (Employee) principals.getPrimaryPrincipal();

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		if (currentUser.getAdmin()) {
			info.addRole("ADMIN");
			info.addStringPermission("*:*");
		} else {
			//获取用户拥有的角色的name集合
			List<String> roleNames = roleService.getRoleNameByEmployeeId(currentUser.getId());
			//获取用户的resource集合
			List<String> currentUserResources = permissionService.getResourceByEmployeeId(currentUser.getId());
			info.addRoles(roleNames);
			info.addStringPermissions(currentUserResources);
		}
		return info;
	}

	/**
	 * 认证
	 *
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取登陆的用户信息
		String username = (String) token.getPrincipal();
		//检验
		Employee employee = employeeService.getByUsername(username);
		if (employee == null) {
			return null;
		}

		SimpleAuthenticationInfo simpleAuthenticationInfo =
				new SimpleAuthenticationInfo(employee, employee.getPassword(),
						ByteSource.Util.bytes(employee.getUsername()), getName());
		return simpleAuthenticationInfo;
	}

}
